package com.example.yichuangyun.mvvm.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ItemCompanyNameBinding;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.CompanyDataModel;
import com.example.yichuangyun.model.business.CompanyModel;
import com.example.yichuangyun.mvvm.ui.activity.AddContactsActivity;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CompanyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private List<CompanyModel> data;
    private final OnCompanyButtonChangeListener onCompanyButtonChangeListener;
    private final List<String> companyData = new ArrayList<>();
    private int flag;
    private String companyName, creditNo;

    public CompanyAdapter(Context context, List<CompanyModel> data, OnCompanyButtonChangeListener onCompanyButtonChangeListener) {
        this.context = context;
        this.data = data;
        this.onCompanyButtonChangeListener = onCompanyButtonChangeListener;
        companyData.add(context.getString(R.string.established));
        companyData.add(context.getString(R.string.to_be_established));
    }

    public CompanyAdapter(Context context, List<CompanyModel> data, OnCompanyButtonChangeListener onCompanyButtonChangeListener, int flag) {
        this.context = context;
        this.data = data;
        this.onCompanyButtonChangeListener = onCompanyButtonChangeListener;
        this.flag = flag;
        companyData.add(context.getString(R.string.established));
        companyData.add(context.getString(R.string.to_be_established));
        if (data.size() > 0 && !TextUtils.isEmpty(data.get(0).getCompName()) && !TextUtils.isEmpty(data.get(0).getCreditNo())) {
            companyName = data.get(0).getCompName();
            creditNo = data.get(0).getCreditNo();
        }
    }

    public void onRefresh(List<CompanyModel> mList) {
        if (mList != null) {
            if (data == null) {
                data = new ArrayList<>();
            }
            this.data.clear();
            this.data.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemCompanyNameBinding itemCompanyNameBinding = ItemCompanyNameBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ContactWayViewHolder(itemCompanyNameBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ContactWayViewHolder) {
            ContactWayViewHolder contactWayViewHolder = (ContactWayViewHolder) holder;
            CompanyModel model = data.get(position);
            if (model.getCompanyStatus() == 1) {
                contactWayViewHolder.binding.tvRelationCompany.setText(context.getString(R.string.established));
                contactWayViewHolder.binding.textCompanyNameText.setText(context.getString(R.string.company_name_star));
            } else if (model.getCompanyStatus() == 2) {
                contactWayViewHolder.binding.tvRelationCompany.setText(context.getString(R.string.to_be_established));
                contactWayViewHolder.binding.textCompanyNameText.setText(context.getString(R.string.company_name));
            } else {
                contactWayViewHolder.binding.tvRelationCompany.setText("");
                contactWayViewHolder.binding.textCompanyNameText.setText(context.getString(R.string.company_name));
            }

            if (model.getIsPublic() == 1) {
                contactWayViewHolder.binding.rbPublic.setChecked(true);
            } else {
                contactWayViewHolder.binding.rbHide.setChecked(true);
            }

            contactWayViewHolder.binding.ivAddInfo.setBackgroundResource(position == 0 ? R.drawable.shape_add_number : R.drawable.shape_del_bg_bbc2cb);
            contactWayViewHolder.binding.ivAddInfo.setImageResource(position == 0 ? R.mipmap.icon_add_write : R.mipmap.icon_reduce_write);
            contactWayViewHolder.binding.ivAddInfo.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                if (position == 0) {
                    data.add(new CompanyModel());
                } else {
                    data.remove(model);
                }
                notifyDataSetChanged();
                onCompanyButtonChangeListener.onCompanyChangeListener(data);
            });

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (contactWayViewHolder.binding.etCompanyName.getTag() instanceof TextWatcher) {
                contactWayViewHolder.binding.etCompanyName.removeTextChangedListener((TextWatcher) (contactWayViewHolder.binding.etCompanyName.getTag()));
            }
            // 第2步：移除TextWatcher之后，设置EditText的Text。
            contactWayViewHolder.binding.etCompanyName.setText(model.getCompName());

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (flag == 2) {
                        if (editable.toString().equals(companyName)) {
                            model.setCreditNo(creditNo);
                        }
                        if (!TextUtils.isEmpty(model.getCreditNo())) {
                            if (creditNo.equals(model.getCreditNo())) {
                                model.setCreditNo(editable.toString().equals(companyName) ? creditNo : null);
                            } else {
                                model.setCreditNo(model.getCreditNo());
                            }
                        }
                    }
                    model.setCompName(TextUtils.isEmpty(editable.toString()) ? "" : editable.toString());
                    onCompanyButtonChangeListener.onCompanyChangeListener(data);
                }
            };
            contactWayViewHolder.binding.etCompanyName.addTextChangedListener(watcher);
            contactWayViewHolder.binding.etCompanyName.setTag(watcher);

            contactWayViewHolder.binding.etCompanyName.setOnEditorActionListener((v, actionId, event) -> {
                if (CommonUtil.isCanClick()) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        String companyName = contactWayViewHolder.binding.etCompanyName.getText().toString();
                        if (!TextUtils.isEmpty(companyName)) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("keyword", companyName);
                            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getCompanyByQxb(requestBody), new MyObserver<HttpRespond<CompanyDataModel>>() {
                                @Override
                                protected void onSuccess(HttpRespond<CompanyDataModel> companyDataModelHttpRespond) {
                                    if (Constant.SUCCESS == companyDataModelHttpRespond.code) {
                                        if (null != companyDataModelHttpRespond.data) {
                                            List<CompanyDataModel.CompanyInfoModel> list = companyDataModelHttpRespond.data.getItems();
                                            if (null != list && list.size() > 0) {
                                                List<String> mComList = new ArrayList<>();
                                                for (CompanyDataModel.CompanyInfoModel comModel : list) {
                                                    mComList.add(comModel.getName() /* + "(" + comModel.getCreditNo() + ")" */);
                                                }
                                                CommonUtil.closeKeyboard((AddContactsActivity) context);
                                                SinglePickerView singlePickerView = new SinglePickerView((AddContactsActivity) context, context.getString(R.string.choose_company), mComList) {
                                                    @Override
                                                    public void confirm(String label, int position) {
                                                        model.setCompName(list.get(position).getName());
                                                        model.setCreditNo(list.get(position).getCreditNo());
                                                        notifyDataSetChanged();
                                                    }
                                                };
                                                singlePickerView.showSinglePickerView();
                                            } else {
                                                model.setCreditNo(null);
                                            }
                                        }
                                    }
                                }
                            });
                        } else {
                            model.setCreditNo(null);
                        }
                        return true;
                    }
                }
                return false;
            });

            contactWayViewHolder.binding.rlRelationCompany.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                SinglePickerView singlePickerView = new SinglePickerView((Activity) context, context.getString(R.string.company_status), companyData) {
                    @Override
                    public void confirm(String label, int position1) {
                        // 状态  1、已设立 2、拟设立
                        int status = label.equals(context.getString(R.string.established)) ? 1 : 2;
                        if (status == 2) {
                            model.setCompName("");
                            model.setCreditNo(null);
                        }
                        model.setCompanyStatus(status);
                        notifyItemChanged(holder.getAbsoluteAdapterPosition());
                        onCompanyButtonChangeListener.onCompanyChangeListener(data);
                    }
                };
                singlePickerView.showSinglePickerView();
            });

            contactWayViewHolder.binding.radioGroup.setOnCheckedChangeListener((radioGroup, checkedId) -> model.setIsPublic(checkedId == R.id.rb_public ? 1 : 0));
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    static class ContactWayViewHolder extends RecyclerView.ViewHolder {

        ItemCompanyNameBinding binding;

        public ContactWayViewHolder(ItemCompanyNameBinding itemCompanyNameBinding) {
            super(itemCompanyNameBinding.getRoot());
            binding = itemCompanyNameBinding;
        }
    }

    public interface OnCompanyButtonChangeListener {
        void onCompanyChangeListener(List<CompanyModel> list);
    }
}
